package com.example.demo1122.service.impl;


import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo1122.domain.ResponseResult;
import com.example.demo1122.entity.Course;
import com.example.demo1122.entity.Question;
import com.example.demo1122.mapper.ConversationMapper;
import com.example.demo1122.mapper.CourseMapper;
import com.example.demo1122.mapper.QuestionMapper;
import com.example.demo1122.service.IQuestionService;
import com.example.demo1122.utils.QwenStreamCall;
import io.reactivex.Flowable;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Resource
    private  QuestionMapper questionMapper;
    @Resource
    private ConversationMapper conversationMapper;
    @Resource
    private CourseMapper courseMapper;
    @Autowired
    private AsyncService asyncService;


    @Override
    @Transactional // 保证数据库原子操作
    public ResponseResult askLLM(Question question) {
        question.setQuestionEvaluation(2); // 默认设置未评价为2
        String questionContent = question.getQuestionContent();
        if(questionContent == null){
            return new ResponseResult(0,"error","未输入提问内容，请重新输入");
        }
        // 查询历史上下文
        Integer conversationID = question.getConversationID();
        List<Question> questionList = questionMapper.selectAllByConversationID(conversationID);
        // 没有上文，说明是问的第一个问题，取前十个字作为标题
        // 获取提问的相关课程名用于初始化LLM system role
//        String courseName = conversationMapper.getCourseNameByID(conversationID);
        Course course = courseMapper.getCourseInfo(conversationID);
        String sysRole = course.getSysRole();
        if (sysRole == null || sysRole.length() == 0){
            sysRole = String.format("你是一位老师，教授的课程是%s，若该课程有对应编程语言，请在回答学生代码问题时使用该语言作答。若是c语言课程，请不要使用c++作答。", course.getCourseName());
        }
        String title = "新建会话";
        if (questionList.size() == 0){
            if (questionContent.length() <= 10){
                title = questionContent;
            }
            else {
                title = questionContent.substring(0,10);
            }
            conversationMapper.addTitle(conversationID, title);
        }
        try {
            String LLMResult = QwenStreamCall.streamCallWithMessage(sysRole, questionList, questionContent);
            question.setAnswerContent(LLMResult);
            questionMapper.insert(question);
            HashMap<String, Object> askMap = new HashMap<>();
            askMap.put("questionID", question.getQuestionID());
            askMap.put("answerContent", LLMResult);
            return new ResponseResult(1,"success",askMap);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            return new ResponseResult(0, "error",e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseResult selectConversationQuestion(Integer conversationID){
        if (!questionMapper.isConversationIDExists(conversationID)){
            return new ResponseResult(0, "error", "会话不存在");
        }
        try {
            List<Question> questionList =  questionMapper.selectAllByConversationID(conversationID);
            HashMap<String, List<Question>> questionMap = new HashMap<>();
            questionMap.put("data", questionList);
            return new ResponseResult(1, "success", questionMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    public ResponseResult getQuestionNum(Integer conversationID){
        try{
            Integer questionNum = questionMapper.getQuestionNum(conversationID);
            HashMap<String, Integer> questionNumMap = new HashMap<>();
            questionNumMap.put("questionNum", questionNum);
            return new ResponseResult(1, "success", questionNumMap);
        }catch (Exception e){
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    public ResponseResult evaluateQuestion(Question question){
        if (question.getQuestionEvaluation() != 0 && question.getQuestionEvaluation() != 1){
            return new ResponseResult(0, "error", "对回答的评价输入有误");
        }
        try {
            questionMapper.update(question);
            return new ResponseResult(1, "success");
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }

    @Override
    @Transactional
    public ResponseResult showConversation(Integer conversationID) {
        if (!questionMapper.isConversationIDExists(conversationID)){
            return new ResponseResult(0, "error", "会话不存在");
        }
        try {
            QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
            questionQueryWrapper.eq("conversationID", conversationID);
            List<Question> questionList = questionMapper.selectList(questionQueryWrapper);
            HashMap<String, List<Question>> showConversationMap = new HashMap<>();
            showConversationMap.put("data", questionList);
            return new ResponseResult(1, "success", showConversationMap);
        } catch (Exception e) {
            return new ResponseResult(0, "error", e);
        }
    }


/*    @Override
    @Transactional
    public Flowable<GenerationResult> askLLM_stream(Question question) {
        question.setQuestionEvaluation(2); // 默认设置未评价为2
        String questionContent = question.getQuestionContent();
        // 查询历史上下文
        Integer conversationID = question.getConversationID();
        List<Question> questionList = questionMapper.selectAllByConversationID(conversationID);
        // 没有上文，说明是问的第一个问题，取前十个字作为标题
        // 获取提问的相关课程名用于初始化LLM system role
        String courseName = conversationMapper.getCourseNameByID(conversationID);
        String sysRole = String.format("你是一位%s老师", courseName);
        String title = "新建会话";
        if (questionList.size() == 0){
            if (questionContent.length() <= 10){
                title = questionContent;
            }
            else {
                title = questionContent.substring(0,10);
            }
            conversationMapper.addTitle(conversationID, title);
        }
        try {
            Flowable<GenerationResult> LLMResult = QwenStreamCall.streamCallWithMessage_stream(sysRole, questionList, questionContent);
            // 调用异步方法将回答存入数据库
            asyncService.logAnswer(question, LLMResult);
            return LLMResult;
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.print(e);
            return null;
        }
    }
    */

}
